package com.young.simpleweb.config;

import com.young.common.frame.Result;
import com.young.common.frame.ResultCode;
import com.young.common.frame.ServiceException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Controller异常统一处理
 * 对于其他层面 如：Interceptor抛出的异常无能为力
 * {@link CommonHandlerExceptionResolver}不处理的情况下，这里处理
 *
 * @author ：<a href="mailto:youngkun2016@163.com">young</a>
 * @date ：Created in 2020/3/28
 */
@RestControllerAdvice
public class ControllerExceptionHandle {
    private static Logger logger = LogManager.getLogger(ControllerExceptionHandle.class);

    /**
     * Controller层面异常兜底
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e) {
        Result result = new Result();
        result.setCode(ResultCode.FAIL);
        if (e instanceof ServiceException) {
            result.setMessage(e.getMessage());
        } else {
            logger.error("【未知异常】{}", e);
            result.setMessage("未知异常");
        }
        return result;
    }
}
